package org.domain.sigepac.home;

import java.util.ArrayList;
import java.util.List;

import net.sf.trugger.reflection.Reflection;

import org.domain.sigepac.Entity.EntidadeAbstrata;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.framework.EntityQuery;


public abstract class EntityQuerySupport<E extends EntidadeAbstrata> extends
		EntityQuery<E> {

	private static final long serialVersionUID = 828857799636859567L;

	private Class<E> entityClass;

	private E entity;
	private String beginOutcome;
	private String endOutcome;

	@In(create = true, required = false)
	@Out(required = false, scope = ScopeType.CONVERSATION, value = "result")
	protected List<E> result;

	public EntityQuerySupport() {
		entityClass = Reflection.reflect().genericType("E").in(this);
		entity = createEntity();

		QuerySupport annotation = getClass().getAnnotation(QuerySupport.class);
		initEjbql(annotation);

		beginOutcome = annotation.beginOutcome();
		endOutcome = annotation.endOutcome();

		setRestrictionLogicOperator("and");
		setRestrictionExpressionStrings(recuperaRestricoes());

		if(!annotation.order().isEmpty()) {
		  setOrder(annotation.order());
		}
    if(!annotation.groupBy().isEmpty()) {
      setGroupBy(annotation.groupBy());
    }
	}

	private void initEjbql(QuerySupport annotation) {
		String ejbql = annotation.ejbql();
		if (ejbql.isEmpty()) {
			ejbql = String.format("from %s", entityClass.getSimpleName());
		}
		setEjbql(ejbql);
	}

	protected E createEntity() {
		return Reflection.newInstanceOf(entityClass);
	}

	protected List<String> recuperaRestricoes() {
		return new ArrayList<String>();
	}

	public String queryAction() {
		result = getResultList();
		return null;
	}

	@Begin(join = true)
	public String begin() {
		result = getResultList();

		return beginOutcome;
	}

	@End
	public String end() {
		return endOutcome;
	}

	public E getEntity() {
		return entity;
	}

	public void setEntity(E entity) {
		this.entity = entity;
	}

}
